#ifndef xpack_graphic_algo_binarization0
#define xpack_graphic_algo_binarization0
#pragma push_macro("xuser")
#undef  xuser
#define xuser mixc::graphic_algo_binarization0::inc
#include"define/base_type.hpp"
#include"macro/xexport.hpp"
#pragma pop_macro("xuser")

namespace mixc::graphic_algo_binarization0::origin{
    struct binarization0_pack{
        uxx     x_start = 0;
        uxx     y_start = 0;
        uxx     width;
        uxx     height;

        // 值越小，画面越亮，噪点越少，但细节也会丢失
        // 值越大，画面越暗，噪点越多，细节稍微多点
        // 算法设计要求 dark_value / 4096 <= 1/9
        // 推荐范围 350~455，可以根据实际需要调整
        uxx     dark_value = 410;
    };

    inline void binarization0(
        auto                    const & input, 
        binarization0_pack      const & pack,
        auto                    const & randerx
    ){
        constexpr uxx r_w               = 3;
        constexpr uxx r_h               = 3;
        auto width                      = pack.width;
        auto height                     = pack.height;
        auto x_start                    = pack.x_start;
        auto y_start                    = pack.y_start;
        auto x_end                      = uxx(x_start + width) / r_w * r_w;
        auto y_end                      = uxx(y_start + height) / r_h * r_h;
        auto dark_value                 = pack.dark_value;

        for(uxx y = y_start; y + 2 < y_end; y++){
            for(uxx x = x_start; x + 2 < x_end; x++){
                uxx sum                 = 0;
                uxx mid_brightness      = 0;

                for(uxx i = 0; i < r_h; i++){
                    for(uxx j = 0; j < r_w; j++){
                        auto nx         = x + j;
                        auto ny         = y + i;
                        auto v          = input[ny][nx];
                        auto brightness = uxx(v->red * 3 + v->green * 6 + v->blue * 1);
                        sum            += brightness;

                        if (i == 1 and j == 1){
                            mid_brightness = brightness;
                        }
                    }
                }

                // 比 1/9 小一些即可
                // 这里使用除法优化，分数接近于一个小于 1/9 的值，除以 4096 一般会被优化成移位操作
                if (auto avg = uxx(sum) * dark_value / 4096; avg > mid_brightness){
                    randerx(x + 1, y + 1, u08(0x00));
                }
                else{
                    randerx(x + 1, y + 1, u08(0xff));
                }
            }
        }
    }
}

#endif

xexport_space(mixc::graphic_algo_binarization0::origin)
